package org.design.environmentprotection.util;

import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static android.provider.Settings.System.DATE_FORMAT;

public class LogUtil {

    public static boolean isDebug = true;

    /**
     * 日志文件最大长度
     */
    private static final long MAX_LOG_FILE_LEN = 1024 * 1024 * 10;
    private final static String APP_TAG = "face_recognition";

    /**
     * 获取相关数据:类名,方法名,行号等.用来定位行<br>
     * at cn.utils.MainActivity.onCreate(MainActivity.java:17) 就是用來定位行的代碼<br>
     *
     * @return [ Thread:main, at
     * cn.utils.MainActivity.onCreate(MainActivity.java:17)]
     */
    private static String getFunctionName() {
        StackTraceElement[] sts = Thread.currentThread().getStackTrace();
        if (sts != null) {
            for (StackTraceElement st : sts) {
                if (st.isNativeMethod()) {
                    continue;
                }
                if (st.getClassName().equals(Thread.class.getName())) {
                    continue;
                }
                return "[ Thread:" + Thread.currentThread().getName() + ", at " + st.getClassName() + "." + st.getMethodName()
                        + "(" + st.getFileName() + ":" + st.getLineNumber() + ")" + " ]";
            }
        }
        return null;
    }


    public static void v(String msg) {
        if (isDebug) {
            Log.v(APP_TAG, getMsgFormat(msg));
        }
    }

    public static void v(String tag, String msg) {
        if (isDebug) {
            Log.v(tag, getMsgFormat(msg));
        }
    }


    public static void d(String msg) {
        if (isDebug) {
            Log.d(APP_TAG, getMsgFormat(msg));
        }
    }

    public static void d(String tag, String msg) {
        if (isDebug) {
            Log.d(tag, getMsgFormat(msg));
        }
    }


    public static void i(String msg) {
        if (isDebug) {
            Log.i(APP_TAG, getMsgFormat(msg));
        }
    }

    public static void i(String tag, String msg) {
        if (isDebug) {
            Log.i(tag, getMsgFormat(msg));
        }
    }


    public static void w(String msg) {
        if (isDebug) {
            Log.w(APP_TAG, getMsgFormat(msg));
        }
    }

    public static void w(String tag, String msg) {
        if (isDebug) {
            Log.w(tag, getMsgFormat(msg));
        }
    }


    public static void e(String msg) {
        if (isDebug) {
            Log.e(APP_TAG, getMsgFormat(msg));
        }
    }

    public static void e(String tag, String msg) {
        if (isDebug) {
            Log.e(tag, getMsgFormat(msg));
        }
    }

    /**
     * 输出格式定义
     */
    private static String getMsgFormat(String msg) {
        return msg + " ;" + getFunctionName();
    }

    /**
     * 将错误日志打印到日志文件中
     * @param filePath
     * @param logInfo
     */
    public static void AppendLogInfo(String filePath, String logInfo)
    {
        Object fileLock = GetLogFileLock(filePath);
        synchronized (fileLock)
        {
            if (filePath != null && !filePath.isEmpty())
            {
                RenameIfTooBig(filePath,MAX_LOG_FILE_LEN);
                File file = new File(filePath);
                PrintStream printStream = null;
                OutputStream os = null;
                if (logInfo == null) logInfo = "null";
                try
                {
                    if (!file.exists())
                    {
                        file.createNewFile();
                    }
                    if (file.exists())
                    {
                        //DateFormat 转换日期形式，是将已知形式的字符串转换为Date形式
                        String time = DATE_FORMAT.format(String.valueOf(new Date()));
                        os = new FileOutputStream(file, true);
                        printStream = new PrintStream(os);
                        printStream.append("\n\n\n\n");
                        printStream.append(time);
                        printStream.append("\n\n");
                        printStream.append(logInfo);
                        os.close();
                        printStream.close();
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                    try
                    {
                        if (printStream != null)
                        {
                            printStream.close();
                        }
                        if (os != null)
                        {
                            os.close();
                        }
                    }
                    catch (Exception e1)
                    {
                        e1.printStackTrace();
                    }
                }
            }
        }
    }
    private final static Map<String, Object> logFileLockMap = new HashMap<String, Object>();
    private static Object GetLogFileLock(String filePath)
    {
        synchronized (logFileLockMap)
        {
            Object lock = logFileLockMap.get(filePath);
            if(lock==null)
            {
                lock = new Object();
                logFileLockMap.put(filePath, lock);

            }
            return lock;
        }
    }

    /**如果连准备备份的文件(.bak)都已经存在，那么这个备份的文件(.bak)会被删除*/
    public static void RenameIfTooBig(String filePath, long fileLen)
    {
        if (filePath != null && !filePath.isEmpty())
        {
            File file = new File(filePath);
            if (file.exists() && file.length() > fileLen)
            {
                file.renameTo(new File(filePath+".bak"));
            }
        }
    }

}
